package alpaca.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * This class helps by encrypting passwords with salt to MD5 hashes.
 */
public class PasswordEncrypter {

	/**
	 * Encrypts a password with a salt to MD5 hash and convert into a hex-string.
	 * @param password 	The password to encrypt.
	 * @return			the encrypted password+salt as a string of hex-integers.
	 */
	public static String encrypt(String password) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("SHA1");
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		if (digest != null) {
			digest.update((password+1337).getBytes()); //TODO: Better Salt
			byte[] hash = digest.digest();
			return toHex(hash);
		}
		else {
			return password;
		}
	}
	
	/**
	 * Found here: 
	 * http://stackoverflow.com/questions/332079/in-java-how-do-i-convert-a-byte-array-to-a-string-of-hex-digits-while-keeping-le
	 * (2011-05-17)
	 */
	private static String toHex(byte[] bytes) {
		BigInteger bigInteger = new BigInteger(1, bytes);
	    return String.format("%0" + (bytes.length << 1) + "x", bigInteger);
	}
	
}
